'''
Author: goog
Date: 2021-12-13 16:45:46
LastEditTime: 2022-01-13 10:32:43
LastEditors: goog
Description: 下段检测只在10号摄像头检测
FilePath: /chengdu/TensorRT20220110/DetectionZM/M/M.py
Time Limit Exceeded!
'''
import json
import os
import cv2
import torch
import numpy as np
from PIL import Image
from torchvision import transforms
from torchvision.models import resnet18
from sklearn.decomposition import PCA



def m(cfg, image, item, net, barcode):
    tmp = cv2.cvtColor(image.copy(), cv2.COLOR_BGR2RGB) 
    defect = "M"
    abs_dir = cfg['abs_dir']
    config_path = os.path.join(abs_dir, 'DetectionZM/'+defect+'/'+defect+'.json')
    
    with open(config_path, 'r') as fp:
        config = json.load(fp)
        if barcode[:3] in ['C50', 'C51', 'C59', 'C54', 'H1H', 'C57', 'H3H']:
            # black
            barcode = 'C50'+barcode[3:]
        elif barcode[:3] in ['C52', 'C60', 'C55', 'H2H', 'C58']:
            #  米色 white
            barcode = 'C60'+barcode[3:]
        elif barcode[:3] in ['C53', 'C61', 'C56']:
            # brown
            barcode = 'C61'+barcode[3:]
        else:
            barcode = 'C50'+barcode[3:]
            print('other type')

            
        label = config[barcode]['color']

    if 'lxzst' in item.keys():

        xmin, ymin, xmax, ymax, _ = item['lxzst'][0]
        if 'R-R' in barcode:
            roi_xmin = max(xmin-300, 0)
            roi_ymin = min(ymin+10, 3648)
        else:
            roi_xmin = min(xmax+30, 5472)
            roi_ymin = min(ymin+50, 3648)
        
        roi1 = tmp[roi_ymin:roi_ymin+224, roi_xmin:roi_xmin+224, :]
        cv2.imwrite(os.path.join(cfg['abs_dir'], 'DetectionZM/'+defect+'/'+defect+'.png'), roi1)
    
        _, color = net.clsSHBColor(roi1, roi1, roi1)
        print(color)
        return label == color
    else:
        return False